<template>
	<div class="system-user-container">
		<el-dialog title="修改用户" v-model="isShowDialog" >
			<el-form ref="editUserFormRef" :model="formData" :rules="formRules" label-width="80px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="登录账号" prop="loginName">
							<el-input v-model="formData.loginName" placeholder="请输入登录账号" readonly clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="用户名称" prop="userName">
							<el-input v-model="formData.userName" placeholder="请输入用户名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="手机号码" prop="phone">
							<el-input v-model="formData.phone" placeholder="请输入手机号码" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="邮箱账号" prop="email">
							<el-input v-model="formData.email" placeholder="请输入邮箱账号" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="用户性别" prop="sex">
							<el-select v-model="formData.sex" placeholder="请选择用户性别" clearable class="w100">
								<el-option label="男" value="0"></el-option>
								<el-option label="女" value="1"></el-option>
								<el-option label="未知" value="2"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="用户状态" prop="status">
							<el-select v-model="formData.status" placeholder="请选择用户状态" clearable class="w100">
								<el-option label="正常" value="0"></el-option>
								<el-option label="停用" value="1"></el-option>
								<el-option label="删除" value="2"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="归属部门" prop="deptName">
							<el-cascader
								placeholder="请选择归属部门"
								v-model="formData.deptId"
								:options="depts"
								:props="{expandTrigger: 'hover', checkStrictly: true, value: 'id', label: 'deptName', children: 'children' }"
								class="w100"
								clearable>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="所属角色" prop="roleIds">
							<el-select v-model="formData.roleIds" multiple filterable remote
								@click="loadRoles()"
                                :remote-method="loadRoles"
								placeholder="请选择所属角色" clearable class="w100">
								<el-option
									v-for="item in roles"
									:key="item.id"
									:label="item.roleName"
									:value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="所在岗位" prop="postIds">
							<el-select v-model="formData.postIds" multiple filterable remote 
								@click="loadPosts()"
                                :remote-method="loadPosts"
								placeholder="请选择所在岗位" clearable class="w100">
								<el-option
									v-for="item in posts"
									:key="item.id"
									:label="item.postName"
									:value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="所处职级" prop="rankIds">
							<el-select v-model="formData.rankIds" multiple filterable remote 
								@click="loadRanks()"
                                :remote-method="loadRanks"
								placeholder="请选择所处职级" clearable class="w100">
								<el-option
									v-for="item in ranks"
									:key="item.id"
									:label="item.rankName"
									:value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="备注">
							<el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel">取 消</el-button>
					<el-button type="primary" @click="onSubmit">保 存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { reactive, toRefs, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { getUser, editUser } from '/@/api/system/user/index';
import { getDeptList } from '/@/api/system/dept/index';
import { getPostList } from '/@/api/system/post/index';
import { getRoleList } from '/@/api/system/role/index';
import { getRankList } from '/@/api/system/rank/index';
import { verifyPhone, verifyEmail } from '/@/utils/toolsValidate';
import { lineToTreeData } from '/@/utils/commonFunction';
export default {
	name: 'user/edit',
	setup(props, context) {
		const editUserFormRef = ref();
		const validPhone = (rule, value, callback) => {
			if(!value){
				return callback(new Error('手机号码不能为空'));
			}
			if(value.indexOf('*') == -1 && !verifyPhone(value)){
				return callback(new Error('请输入正确格式的手机号码'));
			}
			return callback();
		}
		const validEmail = (rule, value, callback) => {
			if(!value){
				return callback(new Error('邮箱账号不能为空'));
			}
			if(value.indexOf('*') == -1 && !verifyEmail(value)){
				return callback(new Error('请输入正确格式的邮箱账号'));
			}
			return callback();
		}
		const state = reactive({
			isShowDialog: false,
			depts: [],
			posts: [],
			roles: [],
			ranks: [],
			formData: {},
			formRules : {
				loginName: {required: true, message: '登录账号不能为空', trigger: 'blur' },
				userName: { required: true, message: '用户名称不能为空', trigger: 'blur' },
				phone: { required: true, validator: validPhone, trigger: 'blur' },
				email: { required: true, validator: validEmail, trigger: 'blur' },
				sex: { required: true, message: '用户性别不能为空', trigger: 'blur' },
				status: { required: true, message: '用户状态不能为空', trigger: 'change' }
			}
		});
		//获取用户
		const loadUser = async (id: string) => {
			await getUser({'id' : id}).then((res) => {
				if(res.code == 0){
					state.formData = Object.assign(state.formData, res.data);
					if(res.data.roles && res.data.roles.length > 0){
						state.roles = res.data.roles;
					}
					if(res.data.posts && res.data.posts.length > 0){
						state.posts = res.data.posts;
					}
					if(res.data.ranks && res.data.ranks.length > 0){
						state.ranks = res.data.ranks;
					}
				}
			});
		}
		//获取部门
		const loadDepts = async () => {
			await getDeptList().then((res) => {
				if(res.code == 0){
					state.depts = lineToTreeData(res.data);
				}
			});
		}
		//获取岗位
		const loadPosts = async (query?: string) => {
			await getPostList({postName: query}).then((res) => {
				if(res.code == 0){
					state.posts = res.data;
				}
			});
		}
		//获取角色
		const loadRoles = async (query?: string) => {
			await getRoleList({roleName: query}).then((res) => {
				if(res.code == 0){
					state.roles = res.data;
				}
			});
		}
		//获取职级
		const loadRanks = async (query?: string) => {
			await getRankList({rankName: query}).then((res) => {
				if(res.code == 0){
					state.ranks = res.data;
				}
			});
		}
		// 打开弹窗
		const openDialog = (row: any) => {
			state.isShowDialog = true;
			if(row){
				state.formData = Object.assign({}, row);
			}
			loadUser(state.formData.id);
			loadDepts();
		};
		// 关闭弹窗
		const closeDialog = (row?: object) => {
			state.isShowDialog = false;
			for(var key in state.formData) {
				state.formData[key] = undefined;
			}
			editUserFormRef.value.resetFields();
			state.depts = [];
			state.posts = [];
			state.roles = [];
			state.ranks = [];
		};
		// 取消
		const onCancel = () => {
			closeDialog();
		};
		// 保存
		const onSubmit = () => {
			editUserFormRef.value.validate(valid => {
				if(valid){
					let deptId = '';
					if(typeof state.formData.deptId == 'string'){
						deptId = state.formData.deptId;
					}else{
						let length = state.formData.deptId?.length;
						deptId = length > 0 ? state.formData.deptId[length - 1] : '';
					}

					let params = {
						id: state.formData.id,
						loginName: state.formData.loginName,
						userName: state.formData.userName.indexOf('*') > -1 ? undefined : state.formData.userName,
						phone: state.formData.phone.indexOf('*') > -1 ? undefined : state.formData.phone,
						email: state.formData.email.indexOf('*') > -1 ? undefined : state.formData.email,
						sex: state.formData.sex,
						status: state.formData.status,
						deptId: deptId,
						postIds: state.formData.postIds,
						roleIds: state.formData.roleIds,
						rankIds: state.formData.rankIds,
						remark: state.formData.remark
					}
					editUser(params).then((res) => {
						if(res.code === 0){
							ElMessage.success('保存成功');
							context.emit('submit');
							closeDialog(); // 关闭弹窗
						}
					});
				}
			});
		};
		
		return {
			editUserFormRef,
			openDialog,
			closeDialog,
			loadPosts,
			loadRoles,
			loadRanks,
			onCancel,
			onSubmit,
			...toRefs(state),
		};
	},
};
</script>
